<?php
require_once( '../../libs/smarty.inc' );
require_once( '../../libs/smt_variables.php' );
require_once( '../../libs/Class_DB.php' );
require_once( '../../libs/Class_ERROR.php' );
require_once( '../../libs/login.inc.php' );
require_once( '../../libs/const.php' );
require_once( '../../libs/page.php' );

$current=1;
if( isset( $_POST['page'] ) && is_numeric( $_POST['page'] ) ){
	$current = $_POST['page'];
	$st = ($current -1) * PAGE_SIZE;
}else{
	$current = 1;
	$st = 0;
}

$company_name = $_POST["company_name"];
$katakana = $_POST["katakana"];
$branch_name = $_POST["branch_name"];
$sal_manager = $_POST["sal_manager"];
$r_date1 = $_POST["r_date1"];
$r_date2 = $_POST["r_date2"];
$u_date1 = $_POST["u_date1"];
$u_date2 = $_POST["u_date2"];

//SQLクエリー
$sql = "SELECT * FROM p_consumer WHERE 1 = 1";

if($company_name != null){
	$sql = $sql." and company_name like '%".$company_name."%'";
}
if($katakana != null){
	$sql = $sql." and katakana like '%".$katakana."%'";
}
if($branch_name != null){
	$sql = $sql." and branch_name like '%".$branch_name."%'";
}
if($sal_manager != null){
	$sql = $sql." and sal_manager like '%".$sal_manager."%'";
}
if($r_date1 != null || $r_date2 != null){
	$sql = $sql." and r_date BETWEEN '".$r_date1."' and '".$r_date2."'";
}
if($u_date1 != null || $u_date2 != null){
	$sql = $sql." and u_date BETWEEN '".$u_date1."' and '".$u_date2."'";
}
$sql = $sql." order by u_date desc ";

$db = new Class_DB;

$head = "顧客番号,会社名,会社（カタカナ）,支店名,種別,セールス担当者,支払条件,登録日,更新日";

$db->query( $sql );

$data = array();

while( $row = $db->fetch() ){
	
	//$row['id'] = 'A' . sprintf('%05d', $row['id']);
	
	$data[] = mb_convert_encoding( sprintf("\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"",
			sprintf('%08d',$row['consumer_id']),
			$row['company_name'],
			$row['katakana'],
			$row['branch_name'],
			$row['category']==1?"法人":"個人",
			$row['sal_manager'],
			$row['payment_term'],
			$row['r_date'],
			$row['u_date']
		),
		"sjis",
		"utf8"
	);
}

$filename = date("YmdHis") . '.csv';

$head = mb_convert_encoding( $head, "sjis", "utf8");


header("Content-Type: application/octet-stream");
header('Content-Disposition: attachment; filename=' . $filename );

print $head;
print "\n";
print implode( $data, "\n" );
?>